<template>
  <div class="my-bids">
    <div class="header">
      <div class="header-content">
        <div class="title-section">
          <div class="title-icon">
            <el-icon size="32"><Document /></el-icon>
          </div>
          <div class="title-text">
            <h2>我的标书</h2>
            <p class="subtitle">管理您的所有标书文档</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" class="new-bid-btn" @click="handleNewBid">
            <el-icon><Plus /></el-icon>
            新建标书
          </el-button>
        </div>
      </div>
    </div>

    <!-- 修改表格容器样式 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="bidsList" style="width: 100%" :height="tableHeight">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="title" label="文件名">
          <template #default="{ row }">
            <div class="file-name" @click="handleEdit(row)">
              <el-icon><Document /></el-icon>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="words" label="字数" width="100">
          <template #default="{row}">
            {{ row?.words }}
          </template> </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="{ row }">
            <span>{{ formatDate(row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380">
          <template #default="{ row }">
            <div class="fragment-actions">
              <el-button 
                type="primary" 
                text 
                size="small" 
                @click="handleEdit(row)"
              >
                <el-icon><View /></el-icon>
                查看
              </el-button>
              
              <el-button
                v-if="row?.is_finally === 1"
                type="primary"
                text
                size="small"
                @click="handleDownload(row)"
              >
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              
              <el-button
                v-else-if="row?.is_finally === 2"
                type="warning"
                text
                size="small"
                disabled
              >
                <el-icon><Loading /></el-icon>
                生成中
              </el-button>
              
              <el-button
                v-else-if="row?.is_finally === -1"
                type="info"
                text
                size="small"
                disabled
              >
                <el-icon><Delete /></el-icon>
                已废弃
              </el-button>
              
              <el-button
                v-else
                type="info"
                text
                size="small"
                disabled
              >
                <el-icon><Clock /></el-icon>
                临时标书
              </el-button>
              
              <el-button 
                type="primary" 
                text 
                size="small" 
                @click="handleEdit(row)"
              >
                <el-icon><EditPen /></el-icon>
                编辑
              </el-button>
              
              <el-button 
                type="danger" 
                text 
                size="small" 
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 修改分页器容器样式 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="getData"
        />
      </div>
    </div>

    <!-- 重命名弹窗 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名标书"
      width="500px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
    >
      <el-form :model="renameForm" ref="renameFormRef">
        <el-form-item label="知识库名称" prop="title" :rules="[{ required: true, message: '请输入知识库名称', trigger: 'blur' }]">
          <el-input v-model="renameForm.title" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="Submit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onBeforeUnmount, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElLoading, ElMessage, FormInstance } from 'element-plus';
import { getBidList, downDocByBid } from '@/api/bid/catalogue';
import axios from 'axios';
import { formatDate } from '@/utils/date';
import { View, Download, Loading, Delete, EditPen, Clock, Plus } from '@element-plus/icons-vue';

// 定义类型
interface BidDocument {
  office_ws?: {
    bid: string;
    words?: number;
  };
  title?: string;
  is_finally?: string;
  create_time?: string;
}

const router = useRouter();
const renameFormRef = ref<FormInstance>();

const bidsList = ref<BidDocument[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 添加表格高度响应式变量
const tableHeight = ref(500); // 默认高度

// 计算表格高度
const calculateTableHeight = () => {
  const windowHeight = window.innerHeight;
  // 减去头部、分页器和其他元素的高度
  tableHeight.value = windowHeight - 200; // 可以根据实际情况调整这个值
};

const getData = async () => {
  if (loading.value) return;

  try {
    loading.value = true;
    const params = {
      page_size: pageSize.value,
      page: currentPage.value
    };

    const res :any = await getBidList(params);
    if (res.code === 200) {
      bidsList.value = res.data?.items
      total.value = res?.data?.total
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

const formatNumber = (num: number): string => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const handleNewBid = () => {
  router.push({
    path: '/dashboard/addTender'
  });
};

const handleEdit = (row:any) => {
  router.push({
    path: '/dashboard/addTender',
    query: { id: row?.bid,is_my_bid:true }
  });
};

// 重命名相关
const renameDialogVisible = ref(false);
const renameForm = ref({
  title: '',
  id: null
});
/* 
const handleRename = (row) => {
  renameForm.value.title = row.title;
  renameForm.value.id = row.id;
  renameDialogVisible.value = true;
}; */

const Submit = async () => {
  // 验证表单数据
  await renameFormRef.value?.validate();
  console.log('重命名为:', renameForm.value.title);
  renameDialogVisible.value = false;
  getData(); // 重新获取列表数据
};

const handleDelete = (row) => {
  console.log('删除', row);
};

const handleDownload = async (row: any) => {
  // 检查状态，提前返回时不需要loading
  if (row?.is_finally === 2) {
    ElMessage.warning('该标书正在生成中，请生成完再进行下载！');
    return;
  } else if (row?.is_finally === -1) {
    ElMessage.warning('该标书已废弃，无法下载！');
    return;
  } else if (row?.is_finally === 0) {
    ElMessage.warning('该标书为临时标书，无法下载！');
    return;
  }

  // 创建 loading 实例
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在准备下载...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const response = await downDocByBid({
      doc_id: row?.bid,
      office_ws: ""
    });

    // 检查响应类型
    if (response.data instanceof Blob) {
      // 获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let filename = row?.title || '标书文档'; // 使用标书标题作为默认文件名
      
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (filenameMatch && filenameMatch[1]) {
          filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
        }
      }

      // 确保文件名有扩展名
      if (!filename.endsWith('.docx')) {
        filename = filename + '.docx';
      }

      // 创建 blob 并下载
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      
      // 延迟清理，确保下载开始
      setTimeout(() => {
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      }, 100);

      ElMessage.success('下载成功');
    } else {
      // 如果不是 blob 类型，说明可能是错误响应
      const reader = new FileReader();
      reader.onload = () => {
        try {
          const result = JSON.parse(reader.result as string);
          ElMessage.error(result.message || '下载失败');
        } catch (e) {
          ElMessage.error('下载失败，请重试');
        }
      };
      reader.readAsText(response.data);
    }
  } catch (error: any) {
    console.error('下载失败:', error);
    ElMessage.error(error?.response?.data?.message || error?.message || '下载失败，请重试');
  } finally {
    // 正确关闭 loading
    loadingInstance.close();
  }
};

// 修改分页相关函数
const handleSizeChange = async (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 切换每页条数时重置到第一页
  await getData();
};

const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  await getData();
};

// 监听分页参数变化
watch(
  [currentPage, pageSize],
  () => {
    getData();
  },
  { immediate: true }
);
const eventSourceInstance = ref<EventSource | null>(null);
onMounted(() => {
  calculateTableHeight();
  window.addEventListener('resize', calculateTableHeight);
  getData();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', calculateTableHeight);
});
</script>

<style lang="scss" scoped>
.my-bids {
  height: 100%;
  padding: 24px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
    flex-shrink: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.9) 100%);
    padding: 12px;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(59, 130, 246, 0.1);
    backdrop-filter: blur(10px);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .title-section {
      display: flex;
      align-items: center;
      gap: 16px;

      .title-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 64px;
        height: 64px;
        background: var(--ai-gradient-primary);
        border-radius: 16px;
        color: white;
        box-shadow: 0 4px 16px rgba(129, 140, 248, 0.3);
      }

      .title-text {
        h2 {
          margin: 0 0 8px 0;
          font-size: 28px;
          font-weight: 700;
          background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }

        .subtitle {
          margin: 0;
          color: #6b7280;
          font-size: 14px;
          font-weight: 500;
        }
      }
    }

    .header-actions {
      .new-bid-btn {
        background: var(--ai-gradient-primary);
        border: none;
        border-radius: 12px;
        padding: 12px 24px;
        font-weight: 600;
        font-size: 14px;
        box-shadow: 0 4px 16px rgba(129, 140, 248, 0.3);
        transition: all 0.3s ease;

        .el-icon {
          margin-right: 8px;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(129, 140, 248, 0.4);
        }
      }
    }
  }

  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.1);
    backdrop-filter: blur(10px);
    overflow: hidden;
  }

  .file-name {
    display: flex;
    align-items: center;
    cursor: pointer;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 8px;
    transition: all 0.3s ease;

    .el-icon {
      color: #3b82f6;
      font-size: 18px;
    }

    span {
      color: #1f2937;
      font-weight: 500;
    }

    &:hover {
      background: rgba(59, 130, 246, 0.08);
      transform: translateY(-1px);
    }
  }

  .fragment-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    justify-content: center;
    position: relative;
    z-index: 9999;
    background: white;
    padding: 8px;
    border-radius: 8px;
    min-width: 220px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    border: 2px solid rgba(59, 130, 246, 0.2);
    margin: -8px;
    transform: scale(1.05);
    
    .el-button {
      color: #6b7280;
      border-radius: 8px;
      padding: 6px 12px;
      font-size: 12px;
      font-weight: 500;
      transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
      min-width: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      position: relative;
      z-index: 11;
      
      &:hover {
        // 移除transform，防止重叠
      }
      
      &.el-button--primary {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(37, 99, 235, 0.1) 100%);
        border: 1px solid rgba(59, 130, 246, 0.25);
        color: #2563eb;
        font-weight: 600;
        
        &:hover {
          background: linear-gradient(135deg, rgba(59, 130, 246, 0.15) 0%, rgba(37, 99, 235, 0.15) 100%);
          border-color: rgba(59, 130, 246, 0.4);
          color: #1d4ed8;
        }
      }
      
      &.el-button--danger {
        background: rgba(239, 68, 68, 0.08);
        border-color: rgba(239, 68, 68, 0.2);
        color: #ef4444;
        
        &:hover {
          background: rgba(239, 68, 68, 0.12);
          border-color: rgba(239, 68, 68, 0.3);
          color: #dc2626;
        }
      }
      
      &.el-button--warning {
        background: rgba(245, 158, 11, 0.08);
        border-color: rgba(245, 158, 11, 0.2);
        color: #f59e0b;
        
        &:hover {
          background: rgba(245, 158, 11, 0.12);
          border-color: rgba(245, 158, 11, 0.3);
          color: #d97706;
        }
      }
      
      &.el-button--info {
        background: rgba(107, 114, 128, 0.08);
        border-color: rgba(107, 114, 128, 0.2);
        color: #6b7280;
        
        &:hover {
          background: rgba(107, 114, 128, 0.12);
          border-color: rgba(107, 114, 128, 0.3);
          color: #4b5563;
        }
      }
      
      .el-icon {
        font-size: 14px;
      }
    }
  }

  :deep(.el-button--text) {
    margin-right: 12px;
    border-radius: 8px;
    padding: 8px 16px;
    font-weight: 500;
    transition: all 0.3s ease;

    &:last-child {
      margin-right: 0;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .pagination-container {
    padding: 20px 24px;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: flex-end;
    flex-shrink: 0;
    border-top: 1px solid rgba(59, 130, 246, 0.1);
  }

  // 表格样式优化
  :deep(.el-table) {
    flex: 1;
    border-radius: 16px;
    overflow: hidden;

    // 表头样式
    .el-table__header-wrapper {
      th {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(29, 78, 216, 0.05) 100%);
        color: #374151;
        font-weight: 600;
        border-bottom: 1px solid rgba(59, 130, 246, 0.1);
        padding: 16px 0;
        font-size: 14px;
      }
    }

    // 表格内容样式
    .el-table__body-wrapper {
      overflow-y: auto;
    }

    // 行样式
    .el-table__row {
      transition: all 0.3s ease;
      border-bottom: 1px solid rgba(59, 130, 246, 0.08);

      &:hover {
        background: rgba(59, 130, 246, 0.04);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
      }

      td {
        padding: 16px 0;
        border-bottom: 1px solid rgba(59, 130, 246, 0.08);
      }
    }
  }

  // 弹窗样式美化
  :deep(.el-dialog) {
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 25px 80px rgba(0, 0, 0, 0.15);
    border: 1px solid rgba(59, 130, 246, 0.1);

    .el-dialog__header {
      background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(29, 78, 216, 0.05) 100%);
      border-bottom: 1px solid rgba(59, 130, 246, 0.1);
      padding: 24px 28px;

      .el-dialog__title {
        color: #1f2937;
        font-weight: 700;
        font-size: 18px;
      }
    }

    .el-dialog__body {
      padding: 28px;
      background: white;
    }

    .el-dialog__footer {
      background: rgba(248, 250, 252, 0.8);
      border-top: 1px solid rgba(59, 130, 246, 0.1);
      padding: 20px 28px;
    }
  }

  // 表单样式美化
  :deep(.el-form-item__label) {
    color: #374151;
    font-weight: 600;
    font-size: 14px;
  }

  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid rgba(59, 130, 246, 0.2);
    border-radius: 10px;
    transition: all 0.3s ease;

    &:hover {
      border-color: rgba(59, 130, 246, 0.3);
    }

    &.is-focus {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }

  // 按钮样式美化
  :deep(.el-button) {
    border-radius: 10px;
    padding: 10px 20px;
    font-weight: 600;
    transition: all 0.3s ease;

    &.el-button--primary {
      background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 50%, #1e40af 100%);
      border: none;
      color: white;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(37, 99, 235, 0.4);
      }
    }

    &.el-button--default {
      background: rgba(255, 255, 255, 0.9);
      border: 1px solid rgba(59, 130, 246, 0.2);
      color: #6b7280;

      &:hover {
        border-color: #3b82f6;
        color: #3b82f6;
        background: rgba(59, 130, 246, 0.05);
        transform: translateY(-1px);
      }
    }
  }

  // 分页器样式美化
  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(59, 130, 246, 0.1);
        color: #3b82f6;
      }

      &.is-active {
        background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
        color: white;
      }
    }

    .btn-prev, .btn-next {
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(59, 130, 246, 0.1);
        color: #3b82f6;
      }
    }
  }
}
</style>
